<template>
	<view>
		<u-card full="true" margin="0rpx" :headStyle="{
      margin:'0rpx', padding: '0rpx', textAlign: 'center', 
      fontSize:'36rpx', fontWeight: 'bold',height:'100rpx',
      lineHeight: '100rpx',backgroundColor: '#7c7c7c'}" :footStyle="{
        margin:'0rpx', padding: '0rpx', textAlign: 'center', 
        fontSize:'36rpx', fontWeight: 'bold',height:'140rpx',
        lineHeight: '100rpx',backgroundColor: '#7c7c7c'}">
			<view slot="head">
				<u-row>
					<u-col span="1">
						<u-icon name="arrow-left" size="48" color="white" @click="goBack()"></u-icon>
					</u-col>
					<u-col span="10">
						<view style="text-align: center;color: white;">
							<text>{{otherNickName}}</text>
						</view>
					</u-col>
					<u-col span="1">
						<u-icon name="more-dot-fill" size="48" color="white" @click="showActionSheet = true"></u-icon>
					</u-col>
				</u-row>
			</view>
			<view slot="body" style="height: 1150rpx;">
				<messageList ref="messageList" :messages="messageList" :currentUserId="myId" :my-avatar="myPic"
					:other-avatar="otherPic" :hasMore="hasMore" @load-more="loadMoreMessages">
				</messageList>
			</view>
			<view slot="foot">
				<u-row>
					<u-col span="1">
						<u-icon size="60" name="/static/icon/yuyin.png" style="margin-top: 20rpx;"></u-icon>
					</u-col>
					<u-col span="8">
						<view style="text-align: center;color: white;padding:20rpx;">
							<u-input v-model="message" :type="text" :border="true" placeholder=' ' focus="true"
								confirm-type="发送" @confirm="sendMessage" @keydown.enter="sendMessage" :custom-style="{
                  color: 'white',
                  height: '70rpx',
                  lineHeight: '70rpx',
                  padding:'0rpx',
                  margin:'0rpx',
                }" />
						</view>
					</u-col>
					<u-col span="3">
						<u-row>
							<u-col span='6'>
								<u-icon size="80" name="/static/icon/emoji.png" style="margin-top: 10rpx;"></u-icon>
							</u-col>
							<u-col span='6'>
								<u-icon size="65" name="/static/icon/more.png" style="margin-top: 18rpx;"></u-icon>
							</u-col>
						</u-row>
					</u-col>
				</u-row>
			</view>
		</u-card>

		<!-- 操作菜单 -->
		<u-action-sheet :list="actionList" v-model="showActionSheet" @click="actionSheetClick"></u-action-sheet>

		<!-- 确认删除对话框 -->
		<u-modal v-model="showDeleteConfirm" :content="deleteConfirmContent" :show-cancel-button="true"
			@confirm="confirmDelete"></u-modal>
	</view>
</template>

<script>
	import {
		create,
		page,
		deleteChat
	} from '../../utils/api/modules/message';
	import MessageList from '../common/message.vue';
	import stomp from '../../utils/stomp';

	export default {
		components: {
			MessageList
		},
		data() {
			return {
				otherId: "",
				myId: "",
				otherPic: "",
				myPic: "",
				otherNickName: "",
				messageList: [],
				message: '',
				stompConnected: false,
				// 操作菜单相关
				showActionSheet: false,
				actionList: [{
					text: '清空聊天记录',
					color: '#ff0000'
				}],
				// 删除确认相关
				showDeleteConfirm: false,
				deleteConfirmContent: '确定要清空与' + this.otherNickName + '的聊天记录吗？',
				currentPage: 1,
				pageSize: 20,
				hasMore: true,
				isLoading: false
			}
		},
		onLoad(options) {
			this.otherId = options.id;
			this.myId = uni.getStorageSync('user').id;
			this.otherPic = options.otherPic;
			this.myPic = uni.getStorageSync('user').pic;
			this.otherNickName = options.otherNickName;
			this.deleteConfirmContent = '确定要清空与' + this.otherNickName + '的聊天记录吗？';

			this.initStomp();
			this.loadMessages();
		},
		methods: {
			goBack() {
				uni.navigateBack();
			},

			initStomp() {
				const wsUrl = 'http://localhost:1110/ZHLG/ws-chat';
				const userId = this.myId;
				const chatId = [this.myId, this.otherId].sort().join('_');

				stomp.init(wsUrl, () => {
					this.stompConnected = true;

					stomp.subscribe(`/topic/chat/${chatId}`, (message) => {
						console.log("收到私人消息:", message);
						this.handleIncomingMessage(message);
					});

				}, (error) => {
					console.error('STOMP连接错误:', error);
					this.stompConnected = false;
				});
			},

			async handleIncomingMessage(rawMessage) {
				try {
					const message = rawMessage;

					if ((message.senderId === this.otherId && message.receiverId === this.myId) ||
						(message.senderId === this.myId && message.receiverId === this.otherId)) {

						const formattedMessage = {
							senderId: message.senderId,
							receiverId: message.receiverId,
							content: message.content,
							contentType: message.contentType,
							createTime: message.createTime
						};

						this.messageList.push(formattedMessage);
						this.$nextTick(() => {
							this.scrollToBottom();
						});
					}
				} catch (e) {
					console.error("【STOMP】解析消息失败:", e);
				}
			},

			scrollToBottom() {
				this.$nextTick(() => {
					if (this.$refs.messageList) {
						this.$refs.messageList.scrollToBottom();
					}
				});
			},

			async loadMessages() {
				this.isLoading = true;

				let oldScrollHeight = 0;
				if (this.currentPage > 1) {
					oldScrollHeight = await this.$refs.messageList.getScrollHeight();
				}

				page({
					chatId: [this.myId, this.otherId].sort().join('_'),
					pageSize: this.pageSize,
					pageNum: this.currentPage,
					currentUserId: this.myId
				}).then(res => {
					if (res && res.length > 0) {
						const sortedRes = res.sort((a, b) => new Date(a.createTime) - new Date(b.createTime));

						if (this.currentPage === 1) {
							this.messageList = sortedRes;
							// 确保初始加载滚动到底部
							this.$nextTick(() => {
								this.scrollToBottom();
							});
						} else {
							this.messageList = [...sortedRes, ...this.messageList];

							this.$nextTick(() => {
								this.$refs.messageList.keepPosition(oldScrollHeight);
							});
						}

						this.hasMore = res.length >= this.pageSize;
					} else {
						this.hasMore = false;
					}

					this.isLoading = false;
				}).catch(err => {
					this.isLoading = false;
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				});
			},

			loadMoreMessages() {
				if (this.isLoading || !this.hasMore) return;

				this.isLoading = true;
				this.currentPage++;
				this.loadMessages().finally(() => {
					this.isLoading = false;
				});
			},

			// 敏感词过滤
			filterSensitiveWords(text) {
				const words = ['傻逼', '垃圾', '妈的'];
				let result = text;
				words.forEach(word => {
					const reg = new RegExp(word, 'gi');
					result = result.replace(reg, '*'.repeat(word.length));
				});
				return result;
			},

			sendMessage() {
				if (!this.message.trim()) return;
				// 敏感词过滤
				const filteredMsg = this.filterSensitiveWords(this.message);
				const newMessage = {
					senderId: this.myId,
					receiverId: this.otherId,
					content: filteredMsg,
					contentType: 1,
					createTime: new Date().toISOString()
				};
				if (this.stompConnected) {
					const chatId = [this.myId, this.otherId].sort().join('_');
					const sent = stomp.send('/app/chat', JSON.stringify({
						senderId: this.myId,
						receiverId: this.otherId,
						chatId: chatId,
						content: filteredMsg,
						contentType: 1
					}), {});
					if (sent) {
						this.message = '';
						this.$nextTick(() => {
							this.scrollToBottom();
						});
					} else {
						uni.showToast({
							title: '发送失败',
							icon: 'none'
						});
					}
				} else {
					create(newMessage).then(res => {
						this.messageList.push(newMessage);
						this.message = '';
						this.$nextTick(() => {
							this.scrollToBottom();
						});
					}).catch(err => {
						uni.showToast({
							title: '发送失败',
							icon: 'none'
						});
					});
				}
			},

			actionSheetClick(index) {
				if (index === 0) {
					this.showDeleteConfirm = true;
				}
			},

			confirmDelete() {
				const chatId = [this.myId, this.otherId].sort().join('_');

				deleteChat({
					chatId: chatId,
					currentUserId: this.myId
				}).then(res => {
					uni.showToast({
						title: '聊天记录已清空',
						icon: 'success'
					});
					this.messageList = [];
				}).catch(err => {
					uni.showToast({
						title: '清空失败',
						icon: 'none'
					});
				});
			}
		},
		onUnload() {
			stomp.disconnect();
		}
	}
</script>
<style>
	/* 添加全局样式 */
</style>